package me
import grails.converters.JSON
import com.mysql.cj.jdbc.MysqlConnectionPoolDataSource
import groovy.sql.Sql
import groovy.json.*
import groovy.json.JsonSlurper

class WidgetController {

	def dataSource

	def renderChart = {


	}


	def renderTable = {
		

	}


	def renderData = {widget->
        def sql = new Sql(dataSource)
        def widgetParam = []
        //widgetParam = sql.rows("select * from chart_param where chart_id = ?",widget.id as Integer)
        

        def results = [dataset:[dimensions:[],source:[]]]
        def ds = new MysqlConnectionPoolDataSource();
        def ip = widget.ip
        def db = widget.db
        def port = widget.port
        def userName = widget.userloginid
        def password = widget.userpassword
        ds.setUser(userName);
        ds.setPassword(password);
        ds.setURL("jdbc:mysql://"+ip+":"+port+"/"+db+"?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8");
        def dSql = new Sql(ds)
        def printColNames = { meta ->
            (1..meta.columnCount).each {
                results.dataset.dimensions.add(meta.getColumnLabel(it))
            }
        }

        def printRow = { row ->
            def hm = [:]
            row.toRowResult().keySet().each{
                hm[it] = row[it]
            }
            //println hm
            results.dataset.source.add(hm)
        }
        
        if (widgetParam.size()>0) {
            widgetParam.each{
                if (it.param_type=="string") {
                    widget.sqlstr = widget.sqlstr.replace("\${"+it.param_name+"}","'${it.param_default}'")
                }
                if (it.param_type=="number") {
                    widget.sqlstr = widget.sqlstr.replace("\${"+it.param_name+"}","${it.param_default}")
                } 
            }
        }

        try {
            dSql.eachRow(widget.sqlstr, printColNames, printRow)
        } catch (e) {
            results = [success:false,message:e.getMessage()]
            println e.getMessage()
        }
        return results
    }

   	def render() {
   		def slurper = new JsonSlurper()
   		def results = [success:true]
        def sql = new Sql(dataSource)
        def wid = params.wid
        def wp = params.wp
        def wcache = params.wcache
        def rows = sql.rows("""select a.*,b.name as theme_name,b.source_info,c.userloginid,
        c.ds_type,c.userpassword,c.port,c.ip,c.db 
        from component_info a
        left join theme_manage_info b on a.theme_id = b.id
        left join data_source_hy_info c on a.data_source_id=c.id
        where a.my_tocken=? """,wid )
        
        println 1111111111
        println wid+" "+rows.size()
        println 2222222222
        
        if (rows.size()!=0){
        	def sourceStr = rows[0].source_str
        	results.themeName = rows[0].theme_name
        	results.themeSource = rows[0].source_info
        	if (sourceStr!=null&&sourceStr!="") {
        		sourceStr = slurper.parseText(sourceStr)
        		if (wcache==null||wcache==""||wcache=="false") {
	        		sourceStr.dataset = renderData(rows[0]).dataset
	        	}
        		results.widgetType = sourceStr.name
        		results.sourceStr = sourceStr
        		/*if (sourceStr.name!=null&&sourceStr.name!="") {

        		} else {
        			
        		}*/
			} else {
				sourceStr = {}
				results.sourceStr = sourceStr
			}
		} else {
			results = [success:false]
		}
        render "success_callback("+JsonOutput.toJson(results)+")"
    }
}
